import 'package:flutter/foundation.dart';
import '../models/show.dart';
import '../models/account.dart';

enum TicketHunterStatus {
  idle,
  running,
  paused,
  error,
}

class TicketHunterProvider extends ChangeNotifier {
  TicketHunterStatus _status = TicketHunterStatus.idle;
  Show? _currentShow;
  double _progress = 0.0;
  String _statusMessage = '准备就绪';
  int _attemptCount = 0;
  int _successCount = 0;
  int _errorCount = 0;
  int _totalAttempts = 0;
  int _totalSuccesses = 0;
  int _totalErrors = 0;
  bool _isHunting = false;

  // Getters
  TicketHunterStatus get status => _status;
  Show? get currentShow => _currentShow;
  double get progress => _progress;
  String get statusMessage => _statusMessage;
  int get attemptCount => _attemptCount;
  int get successCount => _successCount;
  int get errorCount => _errorCount;
  int get totalAttempts => _totalAttempts;
  int get totalSuccesses => _totalSuccesses;
  int get totalErrors => _totalErrors;
  bool get isHunting => _isHunting;
  
  // 兼容性属性
  int get activeTasks => _isHunting ? 1 : 0;
  int get failureCount => _errorCount;

  /// 开始抢票
  Future<void> startHunting({
    required Show show,
    TicketSku? sku,
    required List<Account> accounts,
    Map<String, dynamic>? params,
  }) async {
    if (_isHunting) return;

    _isHunting = true;
    _status = TicketHunterStatus.running;
    _currentShow = show;
    _progress = 0.0;
    _statusMessage = '开始抢票...';
    _attemptCount = 0;
    _successCount = 0;
    _errorCount = 0;
    notifyListeners();

    try {
      // 模拟抢票过程
      for (int i = 0; i < 10; i++) {
        if (!_isHunting) break;
        
        await Future.delayed(const Duration(milliseconds: 500));
        _progress = (i + 1) / 10;
        _attemptCount = i + 1;
        _statusMessage = '正在尝试抢票... (${i + 1}/10)';
        notifyListeners();
      }

      if (_isHunting) {
        _successCount = 1;
        _totalSuccesses++;
        _statusMessage = '抢票成功！';
      }
    } catch (e) {
      _errorCount++;
      _totalErrors++;
      _status = TicketHunterStatus.error;
      _statusMessage = '抢票失败: $e';
    } finally {
      _totalAttempts += _attemptCount;
      if (_isHunting) {
        _status = TicketHunterStatus.idle;
        _isHunting = false;
      }
      notifyListeners();
    }
  }

  /// 停止抢票
  void stopHunting() {
    _isHunting = false;
    _status = TicketHunterStatus.idle;
    _statusMessage = '已停止';
    notifyListeners();
  }

  /// 暂停抢票
  void pauseHunting() {
    if (_status == TicketHunterStatus.running) {
      _status = TicketHunterStatus.paused;
      _statusMessage = '已暂停';
      notifyListeners();
    }
  }

  /// 恢复抢票
  void resumeHunting() {
    if (_status == TicketHunterStatus.paused) {
      _status = TicketHunterStatus.running;
      _statusMessage = '继续抢票...';
      notifyListeners();
    }
  }

  /// 重置统计
  void resetStats() {
    _totalAttempts = 0;
    _totalSuccesses = 0;
    _totalErrors = 0;
    notifyListeners();
  }
}